package com.wsz.security.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.session.security.SpringSessionBackedSessionRegistry;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class SecurityConfiguer extends WebSecurityConfigurerAdapter {


    private FindByIndexNameSessionRepository findByIndexNameSessionRepository;

    @Autowired
    public SecurityConfiguer(FindByIndexNameSessionRepository findByIndexNameSessionRepository) {
        this.findByIndexNameSessionRepository = findByIndexNameSessionRepository;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .rememberMe()
                .and()
                .csrf().disable()
                .sessionManagement() //开启会话管理
                .maximumSessions(1) //设置会话并发数为 1
                //.expiredUrl("/login");//传统web开发被挤下线时跳登录页面
//                .expiredSessionStrategy(even ->{
//                    HttpServletResponse response = even.getResponse();
//                response.setContentType("application/json;charset=UTF-8");
//                    Map<String,Object> data = new HashMap<>();
//                    data.put("status",500);
//                    data.put("msg","账户在其他地方登录");
//                    String s = new ObjectMapper().writeValueAsString(data);
//                    response.getWriter().println(s);
//                    response.flushBuffer();
//                })
                .sessionRegistry(sessionRegistry())
                .maxSessionsPreventsLogin(true);//禁止再次登录
    }

    //创建session同步到redis中的方案
    @Bean
    public SpringSessionBackedSessionRegistry sessionRegistry() {
        return new
                SpringSessionBackedSessionRegistry(findByIndexNameSessionRepository);
    }
}

